package com.gph.saviorframework.es.core.facet.request;

import java.util.ArrayList;
import java.util.List;

import com.gph.saviorframework.es.core.facet.AbstractFacetRequest;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.search.aggregations.AbstractAggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.range.RangeBuilder;
import org.springframework.util.Assert;

@Deprecated
public class RangeFacetRequest extends AbstractFacetRequest {

	public static final String RANGE_INTERNAL_SUM = "range-internal-sum";
	private String field;
	private String keyField;
	private String valueField;

	private List<Entry> entries = new ArrayList<Entry>();

	public RangeFacetRequest(String name) {
		super(name);
	}

	public void setField(String field) {
		this.field = field;
	}

	public void setFields(String keyField, String valueField) {
		this.keyField = keyField;
		this.valueField = valueField;
	}

	public void range(Double from, Double to) {
		entries.add(new DoubleEntry(from, to));
	}

	public void range(String from, String to) {
		throw new UnsupportedOperationException("Native Facet are not supported in Elasticsearch 2.x - use Aggregation");
	}

	public void addRange(Double from, Double to) {
		entries.add(new DoubleEntry(from, to));
	}

	public void addRange(String from, String to) {
		throw new UnsupportedOperationException("Native Facet are not supported in Elasticsearch 2.x - use Aggregation");
	}

	@Override
	public AbstractAggregationBuilder getFacet() {
		Assert.notNull(getName(), "Facet name can't be a null !!!");

		RangeBuilder rangeBuilder = AggregationBuilders.range(getName());
		rangeBuilder.field(StringUtils.isNotBlank(keyField) ? keyField : field );

		for (Entry entry : entries) {
			DoubleEntry doubleEntry = (DoubleEntry) entry;
			rangeBuilder.addRange(validateValue(doubleEntry.getFrom(), Double.NEGATIVE_INFINITY), validateValue(doubleEntry.getTo(), Double.POSITIVE_INFINITY));
		}

		rangeBuilder.subAggregation(AggregationBuilders.extendedStats(INTERNAL_STATS));
		if(StringUtils.isNotBlank(valueField)){
			rangeBuilder.subAggregation(AggregationBuilders.sum(RANGE_INTERNAL_SUM).field(valueField));
		}

		return rangeBuilder;
	}

	private double validateValue(Double value, double defaultValue) {
		return value == null ? defaultValue : value;
	}

	static class DoubleEntry extends Entry<Double> {

		DoubleEntry(Double from, Double to) {
			super(from, to);
		}
	}

	static class StringEntry extends Entry<String> {

		StringEntry(String from, String to) {
			super(from, to);
		}
	}

	static class Entry<T> {

		T from;
		T to;

		Entry(T from, T to) {
			this.from = from;
			this.to = to;
		}

		public T getFrom() {
			return from;
		}

		public T getTo() {
			return to;
		}
	}
}

